<template>
  <q-page class="register flex flex-center">
    <q-form ref="registerRef" class="register-form" @submit.prevent="handleRegister">
      <h3 class="text-center q-mb-lg text-grey-8">管理系统</h3>

      <q-input
        v-model="registerForm.username"
        outlined
        dense
        lazy-rules
        :rules="registerRules.username"
        placeholder="账号"
        class="q-mb-md"
      >
        <template v-slot:prepend>
          <q-icon name="person" />
        </template>
      </q-input>

      <q-input
        v-model="registerForm.password"
        outlined
        dense
        lazy-rules
        :rules="registerRules.password"
        type="password"
        placeholder="密码"
        class="q-mb-md"
        @keyup.enter="handleRegister"
      >
        <template v-slot:prepend>
          <q-icon name="lock" />
        </template>
      </q-input>

      <q-input
        v-model="registerForm.confirmPassword"
        outlined
        dense
        lazy-rules
        :rules="registerRules.confirmPassword"
        type="password"
        placeholder="确认密码"
        class="q-mb-md"
        @keyup.enter="handleRegister"
      >
        <template v-slot:prepend>
          <q-icon name="lock" />
        </template>
      </q-input>

      <div class="row q-mb-md" v-if="captchaEnabled">
        <q-input
          v-model="registerForm.captcha"
          outlined
          dense
          lazy-rules
          :rules="registerRules.captcha"
          placeholder="验证码"
          class="col-8"
          @keyup.enter="handleRegister"
        >
          <template v-slot:prepend>
            <q-icon name="verified" />
          </template>
        </q-input>

        <div class="col-4 flex flex-center">
          <q-img :src="codeUrl" @click="getCode" class="register-captcha-img cursor-pointer" />
        </div>
      </div>

      <q-btn type="submit" color="primary" size="lg" class="full-width q-mb-md" :loading="loading">
        <span v-if="!loading">注 册</span>
        <span v-else>注 册 中...</span>
      </q-btn>

      <div class="text-right">
        <router-link class="text-primary" :to="'/login'">使用已有账户登录</router-link>
      </div>
    </q-form>

    <!-- 底部 -->
    <div class="el-register-footer absolute-bottom text-center text-white">
      <span>Copyright © 2018-2022 yuantest All Rights Reserved.</span>
    </div>
  </q-page>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useQuasar } from 'quasar'
import { getCodeImg, register } from '@/api/sys/login'

const $q = useQuasar()
const router = useRouter()

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  id: '',
})

const equalToPassword = (val) => {
  return val === registerForm.value.password || '两次输入的密码不一致'
}

const registerRules = {
  username: [
    (val) => !!val || '请输入您的账号',
    (val) => (val.length >= 2 && val.length <= 20) || '用户账号长度必须介于 2 和 20 之间',
  ],
  password: [
    (val) => !!val || '请输入您的密码',
    (val) => (val.length >= 5 && val.length <= 20) || '用户密码长度必须介于 5 和 20 之间',
  ],
  confirmPassword: [(val) => !!val || '请再次输入您的密码', equalToPassword],
  captcha: [(val) => !!val || '请输入验证码'],
}

const codeUrl = ref('')
const loading = ref(false)
const captchaEnabled = ref(true)
const registerRef = ref(null)

async function handleRegister() {
  try {
    const valid = await registerRef.value.validate()
    if (valid) {
      loading.value = true
      await register(registerForm.value)

      $q.dialog({
        title: '系统提示',
        message: `<span class="text-red">恭喜你，您的账号 ${registerForm.value.username}  注册成功！</span>`,
        html: true,
        ok: {
          color: 'positive',
          label: '确定',
        },
      }).onOk(() => {
        router.push('/login')
      })
    }
  } catch (error) {
    loading.value = false
    if (captchaEnabled.value) {
      getCode()
    }
  }
}

async function getCode() {
  try {
    const response = await getCodeImg()
    captchaEnabled.value =
      response.data.captchaEnabled === undefined ? true : response.data.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + response.data.img
      registerForm.value.id = response.data.id
    }
  } catch (error) {
    console.error(' 获取验证码失败:', error)
  }
}

getCode()
</script>
<style lang="scss" scoped>
.register {
  height: 100vh;
  background-image: url('../assets/images/login-background.jpg');
  background-size: cover;
}

.register-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px;
}

.register-captcha-img {
  height: 40px;
  padding-left: 12px;
}

.el-register-footer {
  height: 40px;
  line-height: 40px;
  width: 100%;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
